import router from '@/router'
import menuList from '@/stores/menu'
import type { RouteRecordRaw } from 'vue-router'

router.beforeEach(async(to, from, next) => {
    if (to.path == '/login') {
        next()
    }
    const token = localStorage.getItem('token')
    if (!token) {
        if (menuList().allowMenu.length === 0) {
            const menus: any = await menuList().generateRoutes()
            menus.map((menu: RouteRecordRaw) => {
                router.addRoute(menu)
            })
            router.addRoute({ path: '/:catchall(.*)', redirect: '/404' })
            next({ ...to, replace: true })
        } else {
            next()
        }
    } else {
        next(`/login?redirect=${to.path}`)
    }
})
